import { getStarList } from '@/api'
import { DefaultPagination, PageSizes, gridSpacing } from '@/store/constant'
import { StarItem } from '@/types/common'
import MainCard from '@/ui-component/cards/MainCard'
import useColumns from './useColumns'
import { GridRowModel } from '@mui/x-data-grid-pro'

const index = () => {
  const theme = useTheme()
  const matches = useMediaQuery(theme.breakpoints.up('lg'))
  const [paginationModel, setPaginationModel] = useState(DefaultPagination)
  const [reqParams, setReqParams] = useState({
    star_id: ''
  })
  // 获取列表，pickBy过滤 false、null、undefined、0、空字符串等
  const { data, refresh, loading } = useRequest(
    () => getStarList(pickBy({ page: paginationModel.page + 1, size: paginationModel.pageSize, ...reqParams })),
    {
      cacheKey: `/star/list?page=${paginationModel.page + 1}`,
      debounceWait: 500,
      refreshDeps: [paginationModel, reqParams],
      onSuccess(res) {
        if (res) {
          const list = (res?.data ?? []) as StarItem[]
          setRows(list)
        }
      }
    }
  )
  const columns = useColumns({ refresh })

  const [rows, setRows] = useState<StarItem[]>([])

  const onReqParamsChange = (key: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
    setReqParams({
      ...reqParams,
      [key]: e.target.value
    })
  }

  return (
    <MainCard
      title={
        <Grid container>
          <Grid container item xs={12} md={4}>
            <Stack sx={{ width: '100%' }} direction="row" alignItems="center" spacing={1}>
              <TextField
                sx={{ flex: 1 }}
                label="star_id"
                id="star_id"
                value={reqParams.star_id}
                onChange={onReqParamsChange('star_id')}
              />
              <LoadingButton variant="contained" loading={loading} onClick={refresh}>
                Search
              </LoadingButton>
            </Stack>
          </Grid>
        </Grid>
      }
    >
      <Grid container spacing={gridSpacing}>
        <Grid
          item
          xs={12}
          sx={{
            minHeight: 500
          }}
        >
          <DataGridPro
            getRowId={(row: GridRowModel) => `${row.star_id}`}
            pagination
            loading={loading}
            columns={columns}
            rows={rows}
            pageSizeOptions={PageSizes}
            rowCount={data?.total ?? 0}
            paginationModel={paginationModel}
            onPaginationModelChange={setPaginationModel}
            disableRowSelectionOnClick
            paginationMode="server"
            {...(matches && { pinnedColumns: { left: ['name'], right: ['actions'] } })}
          />
        </Grid>
      </Grid>
    </MainCard>
  )
}

export default index
